package com.desksoft.ecommerce.util.sequence;

import com.desksoft.ecommerce.entity.mall.dto.Keytable;
import com.desksoft.ecommerce.service.interf.mall.IKeyTableService;
import com.desksoft.ecommerce.util.holder.ApplicationContextHolder;
import com.desksoft.ecommerce.util.result.ServiceResult;

/***************************************
 * <pre>
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: 2013-4-26
 * 创建作者：jh
 * 文件名称：SequenceHelp.java
 * 版本：
 * 功能：
 * 最后修改时间：
 * 修改记录：
 * </pre>
 *****************************************/

public class SequenceHelp {

	
	private static long keyvalue = 1000000;
	private long maxKey; // 当前Sequence载体的最大值
	private long minKey; // 当前Sequence载体的最小值
	private long nextKey; // 下一个Sequence值
	private long poolSize; // Sequence值缓存大小
	private String keyTableName;

	
	
	public String getKeyTableName() {
		return keyTableName;
	}

	public void setKeyTableName(String keyTableName) {
		this.keyTableName = keyTableName;
	}

	public long getMaxKey() {
		return maxKey;
	}

	public void setMaxKey(long maxKey) {
		this.maxKey = maxKey;
	}

	public long getMinKey() {
		return minKey;
	}

	public void setMinKey(long minKey) {
		this.minKey = minKey;
	}

	public synchronized long getNextKey() {
		if (nextKey > maxKey) {
			opeartKeyTable();
		}
		return nextKey++;
	}

	public void setNextKey(long nextKey) {
		this.nextKey = nextKey;
	}

	

	public SequenceHelp(long poolSize, String keyTableName) {
		super();
		this.poolSize = poolSize;
		this.keyTableName = keyTableName;
		opeartKeyTable();
	}

	public long getPoolSize() {
		return poolSize;
	}

	public void setPoolSize(long poolSize) {
		this.poolSize = poolSize;
	}

	private void opeartKeyTable() {
		 IKeyTableService keyTableService = ApplicationContextHolder.get("keyTableService");
		ServiceResult<Keytable> result = keyTableService
				.selectKeyTable(keyTableName);
		if (result.isSuccess()) {
			
			Keytable keytable = result.getResult();
			
			if (keytable != null) {
				
				maxKey = keytable.getKeytablevalue() + poolSize;
				minKey = maxKey - poolSize + 1;
				nextKey = minKey;
				
			}else{
				
				Keytable keytable2 = new Keytable();
				keytable2.setKeytablename(keyTableName);
				maxKey = keyvalue + poolSize;
				keytable2.setKeytablevalue(maxKey);
		        minKey = maxKey - poolSize + 1; 
		        nextKey = minKey; 
				ServiceResult<Boolean> inresult =  keyTableService.insertKeyTable(keytable2);
				if(inresult.isSuccess()){
					return;
				}
			}
			
		}
		Keytable  keytable=new Keytable();
		keytable.setKeytablename(keyTableName);
		keytable.setKeytablevalue(poolSize);
		ServiceResult<Boolean> upresult = keyTableService.updateKeyTable(keytable);
		if(upresult.isSuccess()){
			return;
		}
		
	}
}
